package com.qili.controller.supervisor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qili.util.DateUtil;
import com.qili.util.StringUtil;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;

import java.io.*;
import java.util.*;

/**
 * @author zhaoyongke
 * @date 2021/1/27
 * @description
 */
public class Test {

    public static void main(String[] args) {
        try {
            // creatSealDocument();

            String sourceFile = "D:\\tt\\99.doc";
            String targetFile = "D:\\tt\\99.doc";
            String imageGzurl = "d:\\tt\\pic.jpg";
            String imageQzurl = "d:\\tt\\pic.jpg";

            // String contenttext = "山东正中信息技术股份有限公司";
            String contenttext = "项目经理签字";
            Boolean gz = false;
            Boolean qz = true;
            String qm = "";
            /*   creatSealDocument();*/

           // addStampImageTable(sourceFile, targetFile,   imageGzurl, imageQzurl,"", contenttext, gz, qz);

            addStampBykeyWord(sourceFile, targetFile, "", contenttext);
            HashMap map=new HashMap();
            String str = "{zjl}";
            String json = "[{\"xmjl\":[{\"oper\":\"'w,2'\"},{\"keyword\":\"山东正中信息技术股份有限公司\"}],\"zjl\":[{\"oper\":\"'ta,1'\"},{\"keyword\":\"总监理工程师签字\"}],\"jsfz\":[{\"oper\":\"'ta,1'\"},{\"keyword\":\"技术负责人签字\"}],\"yz\":[{\"oper\":\"'ta,1'\"},{\"keyword\":\"业主单位签字\"}]}]";
            JSONObject jsonObject = (JSONObject)JSONArray.parseArray(json).get(0);
            JSONArray jsonObjectArray =JSONArray.parseArray(jsonObject.get("xmjl").toString());
             for (int i = 0; i < jsonObjectArray.size(); i++) {
                JSONObject  object=(JSONObject)jsonObjectArray.get(i);
                if(i==0){
                    map.put("oper",object.get("oper"));
                }else {
                    map.put("keyword", object.get("keyword"));

                }
            }



            System.out.println( map);


            //sealInWord("D:\\tt\\sign.docx","D:\\tt\\sign.docx","d:\\tt\\101.jpg","山东正中",0,0,300,-30,false);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /*签字盖章 图片效果*/
    public static void creatSealDocument() throws Exception {
        XWPFParagraph currentParagraph = null;
        File fileTem = new File("D:\\tt\\sign.docx");
        InputStream iss = new FileInputStream(fileTem);
        XWPFDocument doc = new XWPFDocument(iss);
        List<XWPFParagraph> xwpfParagraphList = doc.getParagraphs();
        for (int i = 0; i < xwpfParagraphList.size(); i++) {
            XWPFParagraph x = xwpfParagraphList.get(i);
            List<CTBookmark> bookmarkList = x.getCTP().getBookmarkStartList();
            for (int j = 0; j < bookmarkList.size(); j++) {
                System.out.println(bookmarkList.get(j).getName() + "KKKKKKKK");
                if (bookmarkList.get(j).getName().equals("sign")) {
                    currentParagraph = x;
                    break;
                }
            }
        }
        if (currentParagraph != null) {
            //添加印章图片
            XWPFRun run = currentParagraph.createRun();

            String imgFile1 = "d:\\tt\\101.jpg";
            FileInputStream is1 = new FileInputStream(imgFile1);
            run.addPicture(is1, XWPFDocument.PICTURE_TYPE_JPEG, imgFile1, Units.toEMU(60), Units.toEMU(60));
            is1.close();

            CTDrawing drawing1 = run.getCTR().getDrawingArray(0);
            CTGraphicalObject graphicalobject1 = drawing1.getInlineArray(0).getGraphic();
            Random random = new Random();
            int number = random.nextInt(999) + 1;
            //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
            CTAnchor anchor1 = getAnchorWithGraphic(graphicalobject1, "Seal" + number,
                    Units.toEMU(60), Units.toEMU(60),//图片大小
                    Units.toEMU(250), Units.toEMU(0), true);//相对当前段落位置及偏移
            drawing1.setAnchorArray(new CTAnchor[]{anchor1});//添加浮动属性
            drawing1.removeInline(0);//删除行内属性
            //添加签名图片
            run = currentParagraph.createRun();
            imgFile1 = "d:\\tt\\pic.jpg";
            FileInputStream is2 = new FileInputStream(imgFile1);
            run.addPicture(is2, XWPFDocument.PICTURE_TYPE_JPEG, imgFile1, Units.toEMU(60), Units.toEMU(60));
            is2.close();

            random = new Random();
            CTDrawing drawing2 = run.getCTR().getDrawingArray(0);
            CTGraphicalObject graphicalobject2 = drawing2.getInlineArray(0).getGraphic();
            number = random.nextInt(999) + 1;
            CTAnchor anchor2 = getAnchorWithGraphic(graphicalobject2, "Seal" + number,
                    Units.toEMU(60), Units.toEMU(40),//图片大小
                    Units.toEMU(300), Units.toEMU(-5), true);
            drawing2.setAnchorArray(new CTAnchor[]{anchor2});//添加浮动属性
            drawing2.removeInline(0);//删除行内属性

            doc.write(new FileOutputStream("D:\\tt\\sign.docx"));
            iss.close();
        }
        doc.close();
    }

    public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject,
                                                String deskFileName, int width, int height,
                                                int leftOffset, int topOffset, boolean behind) {

        String anchorXML =
                "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
                        + "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
                        + "<wp:simplePos x=\"0\" y=\"0\"/>"
                        + "<wp:positionH relativeFrom=\"column\">"
                        + "<wp:posOffset>" + leftOffset + "</wp:posOffset>"
                        + "</wp:positionH>"
                        + "<wp:positionV relativeFrom=\"paragraph\">"
                        + "<wp:posOffset>" + topOffset + "</wp:posOffset>" +
                        "</wp:positionV>"
                        + "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
                        + "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
                        + "<wp:wrapNone/>"
                        + "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + deskFileName + "\"/><wp:cNvGraphicFramePr/>"
                        + "</wp:anchor>";

        CTDrawing drawing = null;
        try {
            drawing = CTDrawing.Factory.parse(anchorXML);
        } catch (XmlException e) {
            e.printStackTrace();
        }
        CTAnchor anchor = drawing.getAnchorArray(0);
        anchor.setGraphic(ctGraphicalObject);
        return anchor;
    }

    public static CTAnchor getAnchorWithGraphic1(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) {
        String anchorXML = "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"

                + ""

                + ""

                + "" + leftOffset + ""

                + ""

                + ""

                + "" + topOffset + "" +

                ""

                + ""

                + ""

                + ""

                + ""

                + "";
        CTDrawing drawing = null;
        try {
            drawing = CTDrawing.Factory.parse(anchorXML);

        } catch (XmlException e) {
            e.printStackTrace();

        }
        CTAnchor anchor = drawing.getAnchorArray(0);
        anchor.setGraphic(ctGraphicalObject);
        return anchor;
    }


    /**
     * <b> Word中添加图章
     * </b><br><br><i>Description</i> :
     * String srcPath, 源Word路径
     * String storePath, 添加图章后的路径
     * String sealPath, 图章路径（即图片）
     * tString abText, 在Word中盖图章的标识字符串，如：(签字/盖章)
     * int width, 图章宽度
     * int height, 图章高度
     * int leftOffset, 图章在编辑段落向左偏移量
     * int topOffset, 图章在编辑段落向上偏移量
     * boolean behind，图章是否在文字下面
     *
     * @return void
     * <br><br>Date: 2019/12/26 15:12     <br>Author : dxl
     */

    public static void addStampBykeyWord(String sourceFile, String targetFile, String imageurl, String keyword) throws Exception {
        Document doc1 = new Document();
        doc1.loadFromFile(sourceFile);
        doc1.saveToFile(sourceFile, FileFormat.Docx_2013);
        InputStream is = null;
        try {
            XWPFDocument doc;
            doc = new XWPFDocument(new FileInputStream(sourceFile));
            List<XWPFParagraph> paragraphs = doc.getParagraphs();
            XWPFRun targetRun = null;
            XWPFParagraph paragraph1 = null;
            Boolean isfind = false;
            for (XWPFParagraph paragraph : paragraphs) {
                if (!"".equals(paragraph.getText()) && paragraph.getText().contains(keyword)) {
                    List<XWPFRun> runs = paragraph.getRuns();
                    paragraph1 = paragraph;
                    targetRun = runs.get(runs.size() - 1);
                    isfind = true;
                    break;
                }
            }
            if (isfind) {
                if (targetRun != null) {
                    System.out.println("签章操作开始---------------------");
                    InputStream in = new FileInputStream(imageurl);//设置图片路径
                    //创建Random类对象
                    Random random = new Random();
                    //产生随机数
                    int number = random.nextInt(999) + 1;
                    targetRun = paragraph1.createRun();
                    targetRun.addPicture(in, XWPFDocument.PICTURE_TYPE_JPEG, "Seal" + number, Units.toEMU(60), Units.toEMU(60));
                    in.close();
                    // 2. 获取到图片数据
                    CTDrawing drawing = targetRun.getCTR().getDrawingArray(0);
                    CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
                    //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
                    CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "Seal" + number,
                            Units.toEMU(100), Units.toEMU(100),//图片大小
                            Units.toEMU(200), Units.toEMU(-20), false);//相对当前段落位置 需要计算段落已有内容的左偏移
                    drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性
                    drawing.removeInline(0);//删除行内属性
                    System.out.println("签章操作结束---------------------");
                }
            }

            FileOutputStream fos = new FileOutputStream(targetFile);
            doc.write(fos);
            fos.close();
            doc.write(new FileOutputStream(targetFile));
            is = new FileInputStream(targetFile);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os = new FileOutputStream(targetFile);
            document.write(os);
            os.close();
            is.close();
            doc1.close();
            if (!isfind) {
                throw new Exception("没有发现关键字 " + keyword);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("操作失败：" + e.getMessage());

        }
    }


    public static void addStampImageTable(String sourceFile, String targetFile, String imageGzurl,String imageQzurl, String keyword, String contenttext, Boolean gz, Boolean qz) throws Exception {
        Document doc1 = new Document();
        doc1.loadFromFile(sourceFile);
        doc1.saveToFile(sourceFile, FileFormat.Docx_2013);
        XWPFDocument doc;
        Boolean  isFind=false;
        try {
            doc = new XWPFDocument(new FileInputStream(sourceFile));
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {//遍历每一个单元格
                        if (cell.getText().contains(contenttext)) {//如果遇到"&章"则进行替换
                            try {
                                if (StringUtil.isBlank(keyword)) {
                                    keyword = contenttext;
                                }
                                isFind=true;
                                insertCellStamp(cell, imageGzurl,imageQzurl, keyword, gz, qz);//给带有要盖章字样的单元格 加上章的图片
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }

            FileOutputStream fos = new FileOutputStream(targetFile);
            doc.write(fos);
            fos.close();
            doc.write(new FileOutputStream(targetFile));
            InputStream is = new FileInputStream(targetFile);
            XWPFDocument document = new XWPFDocument(is);
            //以上Spire.Doc 生成的文件会自带警告信息，这里来删除Spire.Doc 的警告
            document.removeBodyElement(0);
            //输出word内容文件流，新输出路径位置
            OutputStream os = new FileOutputStream(targetFile);
            document.write(os);
            os.close();
            doc1.close();
            if(!isFind){
                throw new Exception("没有发现关键字 " + keyword);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());

        }
    }


    private static void insertCellStamp(XWPFTableCell cell,String imageGzurl, String imageQzurl, String keyword, Boolean gz, Boolean qz) throws Exception {
        for (XWPFParagraph para : cell.getParagraphs()) {
            //插入图片
            for (int i = 0; i < para.getRuns().size(); i++) {
                try {
                    XWPFRun run = para.getRuns().get(i);
                    String text = run.text();
                    if (text.contains(keyword)) {
                        /*删除盖章关键字*/
                        run.setText(text.replace(keyword, ""), 0);
                        Random random = new Random();
                        int number = random.nextInt(999) + 1;
                        if (gz) {

                            System.out.println("盖章开始------------------------");
                            FileInputStream is1 = new FileInputStream(imageGzurl);
                            run.addPicture(is1, XWPFDocument.PICTURE_TYPE_JPEG, imageGzurl, Units.toEMU(60), Units.toEMU(60));
                            is1.close();
                            CTDrawing drawing1 = run.getCTR().getDrawingArray(0);
                            CTGraphicalObject graphicalobject1 = drawing1.getInlineArray(0).getGraphic();
                            //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
                            CTAnchor anchor1 = getAnchorWithGraphic(graphicalobject1, "Seal" + number,
                                    Units.toEMU(100), Units.toEMU(100),//图片大小
                                    Units.toEMU(10), Units.toEMU(0), true);//相对当前段落位置及偏移
                            drawing1.setAnchorArray(new CTAnchor[]{anchor1});//添加浮动属性
                            drawing1.removeInline(0);//删除行内属性


                            System.out.println("盖章结束------------------------");
                        }

                        if (qz) {
                            //添加签名图片
                            System.out.println("签名开始------------------------");
                            run = para.createRun();
                            FileInputStream is2 = new FileInputStream(imageQzurl);
                            run.addPicture(is2, XWPFDocument.PICTURE_TYPE_JPEG, imageQzurl, Units.toEMU(60), Units.toEMU(60));
                            is2.close();
                            random = new Random();
                            CTDrawing drawing2 = run.getCTR().getDrawingArray(0);
                            CTGraphicalObject graphicalobject2 = drawing2.getInlineArray(0).getGraphic();
                            number = random.nextInt(999) + 1;
                            CTAnchor anchor2 =null;
                            if (!gz) {
                                /*只是盖章*/
                                anchor2 = getAnchorWithGraphic(graphicalobject2, "Seal" + number,
                                        Units.toEMU(60), Units.toEMU(40),//图片大小
                                        Units.toEMU(20), Units.toEMU(-20), false);
                            }else{
                                /*盖章+签字*/
                                anchor2 = getAnchorWithGraphic(graphicalobject2, "Seal" + number,
                                        Units.toEMU(60), Units.toEMU(40),//图片大小
                                        Units.toEMU(20), Units.toEMU(20), false);
                            }

                            drawing2.setAnchorArray(new CTAnchor[]{anchor2});//添加浮动属性
                            drawing2.removeInline(0);//删除行内属性
                            System.out.println("签名结束------------------------");
                        }




                    }
                    if (text.indexOf("年") != -1) {
                        String newtext = text.substring(0, text.indexOf("年")) + DateUtil.formatDate(new Date(), "yyyy年MM月dd日");
                        run.setText(newtext, 0);
                    }
                } catch (Exception e) {
                    System.out.println("Error: ========  插入公章图片时出错了:可能是图片路径不存在");
                    e.printStackTrace();
                    throw new Exception("Error: ========  插入公章图片时出错了:可能是图片路径不存在");

                }
            }
        }
    }
    //浮动于文字上方

    public static void sealInWord(String srcPath, String storePath, String sealPath, String tabText,
                                  int width, int height, int leftOffset, int topOffset, boolean behind) throws Exception {
        File fileTem = new File(srcPath);
        InputStream is = new FileInputStream(fileTem);
        XWPFDocument document = new XWPFDocument(is);
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        XWPFRun targetRun = null;
        for (XWPFParagraph paragraph : paragraphs) {
            if (!"".equals(paragraph.getText()) && paragraph.getText().contains(tabText)) {
                List<XWPFRun> runs = paragraph.getRuns();
                targetRun = runs.get(runs.size() - 1);
            }
        }
        if (targetRun != null) {
            InputStream in = new FileInputStream(sealPath);//设置图片路径
            if (width <= 0) {
                width = 100;
            }
            if (height <= 0) {
                height = 100;
            }
            //创建Random类对象
            Random random = new Random();
            //产生随机数
            int number = random.nextInt(999) + 1;
            targetRun.addPicture(in, XWPFDocument.PICTURE_TYPE_JPEG, "Seal" + number, Units.toEMU(width), Units.toEMU(height));
            in.close();
            // 2. 获取到图片数据
            CTDrawing drawing = targetRun.getCTR().getDrawingArray(0);
            CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();

            //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
            CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "Seal" + number,
                    Units.toEMU(width), Units.toEMU(height),//图片大小
                    Units.toEMU(leftOffset), Units.toEMU(topOffset), behind);//相对当前段落位置 需要计算段落已有内容的左偏移
            drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性
            drawing.removeInline(0);//删除行内属性
        }
        document.write(new FileOutputStream(storePath));
        document.close();

    }


}
